<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="roleQuery.name" placeholder="角色名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="roleQuery.description" placeholder="权限标识" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="roleQuery.status" placeholder="请选择状态" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-date-picker v-model="roleQuery.begin" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="roleQuery.end" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="结束时间" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleAddRole">
        新增角色
      </el-button>
    </div>

    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="角色名" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="权限标识" width="220">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="排序" width="110">
        <template slot-scope="scope">
          {{ scope.row.sort }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="300">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.gmtCreate }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="修改时间" width="300">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.gmtModified }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="Operations">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getRoles" />

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新增角色'" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="role" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="role.name" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="role.description"
            style="width: 300px;"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="role.sort" controls-position="right" :min="1" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="role.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            default-expand-all
            node-key="id"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
// import { deepClone } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getList, remove, save, updateStatus, getRoutes, getRole } from '@/api/role'

export default {
  components: { Pagination },
  data() {
    return {
      total: 0,
      page: 1,
      limit: 10,
      roleQuery: {
        name: '',
        description: '',
        status: '',
        begin: '',
        end: ''
      },
      role: {
        id: undefined,
        name: '',
        description: '',
        sort: '',
        status: true,
        routes: []
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
      },
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      statusOptions: [{ label: '正常', key: 1 }, { label: '停用', key: 0 }]
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    async getRoutes() {
      const res = await getRoutes()
      // this.serviceRoutes = res.data
      this.routes = this.generateRoutes(res.data)
    },
    async getRoles() {
      const res = await getList(this.page, this.limit, this.roleQuery)
      this.rolesList = res.data.records
      this.total = res.data.total
    },

    handleFilter() {
      this.page = 1
      this.getRoles()
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes) {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden && route.type !== 2) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild) {
          route = onlyOneShowingChild
        }
        const data = {
          // path: path.resolve(basePath, route.path),
          id: route.id,
          // title: route.meta && route.meta.title
          title: route.name
        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.resetRole()
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetRole() {
      this.role = {
        id: undefined,
        name: '',
        description: '',
        sort: '',
        status: true,
        routes: []
      }
    },
    async handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      // getRole(row.id).then((res) => {
      //   this.role = res.data
      //   // this.checkStrictly = false
      // })
      const res = await getRole(row.id)
      this.role = res.data
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.tree.setCheckedKeys(this.role.routes)
        this.checkStrictly = false
        // 遍历选中数组,赋值到tree中
        // this.role.routes.forEach(value => {
        //   this.$refs.tree.setChecked(value, true, false)
        // })
      })
      // this.role = deepClone(scope.row)
      // this.$nextTick(() => {
      //   const routes = this.generateRoutes(this.role.routes)
      //   this.$refs.tree.setCheckedNodes(this.generateArr(routes))
      //   // set checked state of a node not affects its father and child nodes
      //   this.checkStrictly = false
      // })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定删除角色?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await remove(row.id)
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    // generateTree(routes, basePath = '/', checkedKeys) {
    //   const res = []

    //   for (const route of routes) {
    //     const routePath = path.resolve(basePath, route.path)

    //     // recursive child routes
    //     if (route.children) {
    //       route.children = this.generateTree(route.children, routePath, checkedKeys)
    //     }

    //     if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
    //       res.push(route)
    //     }
    //   }
    //   return res
    // },
    async confirmRole() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogVisible = false
          const isEdit = this.dialogType === 'edit'
          this.role.routes = this.$refs.tree.getCheckedKeys()
          // const checkedKeys = this.$refs.tree.getCheckedKeys()
          // this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)
          if (isEdit) {
            save(this.role).then((res) => {
              const index = this.rolesList.findIndex(v => v.id === res.data.id)
              this.rolesList.splice(index, 1, res.data)
            })
            // const res = await save(this.role)
            // this.rolesList.unshift(res.data)
            // for (let index = 0; index < this.rolesList.length; index++) {
            //   if (this.rolesList[index].id === this.role.id) {
            //     this.rolesList.splice(index, 1, Object.assign({}, this.role))
            //     break
            //   }
            // }
          } else {
            // const { data } = await save(this.role)
            // this.role.id = data.id
            // this.rolesList.push(res.data)
            save(this.role).then((res) => {
              this.rolesList.unshift(res.data)
            })
            // const res = await save(this.role)
            // this.rolesList.unshift(res.data)
          }
          const { description, name } = this.role
          this.$notify({
            title: 'Success',
            dangerouslyUseHTMLString: true,
            message: `
                <div>Role Name: ${name}</div>
                <div>Description: ${description}</div>
              `,
            type: 'success'
          })
        }
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },
    changeStatus(row) {
      updateStatus(row).then(() => {
        this.$notify({
          title: 'Success',
          message: '状态修改成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
